package org.ezplatform.office.meeting.setting.category.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.ezplatform.component.permission.service.CmpPermissionService;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.office.meeting.setting.boardroom.entity.BoardroomSet;
import org.ezplatform.office.meeting.setting.boardroom.service.BoardroomSetService;
import org.ezplatform.office.meeting.setting.boardroom.web.rest.BoardroomSetWebApiController;
import org.ezplatform.office.meeting.setting.category.dao.BoardroomCategorySetDao;
import org.ezplatform.office.meeting.setting.category.entity.BoardroomCategorySet;
import org.ezplatform.util.SqlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class BoardroomCategorySetService extends BaseService<BoardroomCategorySet, String>{
	private final static Logger LOGGER = LoggerFactory.getLogger(BoardroomCategorySetService.class);
    @Autowired
    private BoardroomCategorySetDao dao;
    @Lazy
    @Autowired
    private BoardroomSetService boardroomSetService;
    @Lazy
    @Autowired
	private CmpPermissionService cmpPermissionService;
    
    @Override
    protected JpaBaseDao<BoardroomCategorySet, String> getEntityDao() {
        return dao;
    }

    public Page getCategorySetList(Pageable localPageable, String corpId, String name,WebUser webUser) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        StringBuffer sql = new StringBuffer();
        sql.append(" select ombcs.id,ombcs.name,ombcs.sort_no,ombcs.is_init ");
        sql.append(" from oa_meeting_boardroom_cate ombcs");
        sql.append(" where ombcs.corp_id=:corpId");
        paramMap.put("corpId", corpId);
        if(StringUtils.isNotBlank(name)){
        	name=SqlUtils.escapeNormalChars(name);
            sql.append(" and ombcs.name like :name "+SqlUtils.getSQLEscape(name));
            paramMap.put("name", "%"+name+"%");
        }
        String perSql = cmpPermissionService.getBusinessScopeSql("ombcs", webUser, "meeting:roomcate:03");
		LOGGER.debug("---perSql:"+perSql);
		sql.append(perSql);
		
        List localList = new ArrayList();
        String sqlStr = PropertyFilter.getSqlByFilterAndPageable("ombcs", sql.toString(), "ombcs.sort_no asc,ombcs.createdDate desc", localList, localPageable);
        Page<Map> localPage = this.findByPageNativeSQL(localPageable, sqlStr, paramMap);
        
        return localPage;
    }

    /**
     * 验证
     * @param id
     * @param checkdata
     * @param type
     * @param corpId
     * @return
     */
    public String checkCategorySet(String id, String checkdata, int type, String corpId) {
        String msg = "";
        List<BoardroomCategorySet> list = new ArrayList<BoardroomCategorySet>();
        if (type == 1) {// 验证名称
            if (StringUtils.isNotBlank(id)) {// 编辑
                list = this.dao.getCategorySetByName(id, checkdata, corpId);
            } else {// 新建
                list = this.dao.getCategorytSetByName(checkdata, corpId);
            }
        }
        if (list != null && list.size() > 0) {
            msg = this.getCheckMsgStr(type);
        }
        return msg;
    }
    
    /**
     * 验证报错返回msg信息
     * 
     * @param type
     * @return
     */
    private String getCheckMsgStr(int type) {
        String msg = "";
        switch (type) {
        case 1:
            msg = "您输入的类型名称已存在";
            break;
        default:
            msg = "";
            break;
        }
        return msg;
    }

    /**
     * 查询会议室类型树数据
     * @param request
     * @param corpId
     * @return
     */
    public String getCategoryTreeData(HttpServletRequest request, String corpId) {
        Map<String, Object> paramMap = new HashMap<String, Object>();

        String sql = "select id,name from oa_meeting_boardroom_cate ";
        sql += " where corp_id = :corpId ";
        paramMap.put("corpId", corpId);
        sql += " ORDER BY sort_no asc,createdDate desc";

        List menuTree = super.getQueryByNativeSQL(sql.toString(), paramMap).getResultList();

        StringBuffer str = new StringBuffer("");
        str.append("[");
        for (int i = 0; i < menuTree.size(); i++) {
            str.append((new StringBuilder()).append("{\"id\":\"").append(((Object[]) menuTree.get(i))[0])
                    .append("\",\"pId\":\"").append("\",\"name\":\"").append(((Object[]) menuTree.get(i))[1])
                    .append("\"},"));
        }

        String str1 = str.toString();
        if (str1.endsWith(","))
            str1 = str1.substring(0, str1.length() - 1);
        str1 = (new StringBuilder()).append(str1).append("]").toString();
        return str1;
    }

    /**
     * 验证分类是否可以删除
     * @param ids
     * @return
     */
	public String checkDeleteData(String[] ids) {
		String msg = "";
		if(ids!=null){
			List<BoardroomCategorySet> bcsList = new ArrayList<BoardroomCategorySet>();
			for(String id:ids){
				List categoryIdList = new ArrayList();
				categoryIdList.add(id);
				List<BoardroomSet> bsList = boardroomSetService.getBoardroomSetList(categoryIdList);
				if(bsList!=null && bsList.size()>0){
					BoardroomCategorySet bcs = this.findOne(id);
					bcsList.add(bcs);
				}
			}
			if(bcsList!=null && bcsList.size()>0){
				for(BoardroomCategorySet bcs : bcsList){
					msg += bcs.getName()+"，";
				}
				msg = msg.substring(0,msg.length()-1);
				msg +="已有会议室使用不可删除";
			}
		}
		return msg;
	}
	
	/**
     * 查询会议室分类
     * @param corpId
     * @return
     */
    public List<BoardroomCategorySet> getCategorySetList(String corpId) {
        List<BoardroomCategorySet> list = this.dao.getCategorySetList(corpId);
        return list;
    }
    
    public List<Map> getHaveRoomCategorySetList(String corpId) {
    	Map<String, Object> paramMap = new HashMap<String, Object>();
        StringBuffer sql = new StringBuffer();
        sql.append("select ombc.id, ombc.name from oa_meeting_boardroom_cate ombc where ombc.corp_id=:corpId");
        sql.append(" and EXISTS (select id from oa_meeting_boardroom_set ombs where ombs.category_id=ombc.id) order by ombc.sort_no");
        paramMap.put("corpId", corpId);
        return super.findByListNativeQuery(sql.toString(), null, paramMap);
    }
    
    public void initData(String corpId) {
    	List<BoardroomCategorySet> initCate = this.dao.getCategoryList(corpId, "1");
    	if(CollectionUtils.isEmpty(initCate)){
    		List<BoardroomCategorySet> categorySets = this.dao.getCategoryList("0","1");
    		if(categorySets!=null && categorySets.size()>0){
    			List<BoardroomCategorySet> newCateList = new ArrayList<BoardroomCategorySet>();
    			for(BoardroomCategorySet ct : categorySets){
    				BoardroomCategorySet categorySet = new BoardroomCategorySet();
    				categorySet.setCorpId(corpId);
    				categorySet.setIsInit("1");
    				categorySet.setName(ct.getName());
    				categorySet.setSortNo(ct.getSortNo());
    				newCateList.add(categorySet);
    			}
    			this.dao.saveAll(newCateList);
    		}
    	}
	}
    
    public void clearData(String corpId) {
		this.dao.delCategoryList(corpId, "1");
	}
    
    public List<BoardroomCategorySet> getCategorytSetByIds(List<String> ids){
    	return this.dao.getCategorytSetByIds(ids);
    }
}